import Axios from 'axios';
import Global from 'system.global';
import qs from 'querystring';

const axiosObj = Axios.create();
const g = Global();
const prePath = g.path || "";

const reqHeader = {
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}

//TODO:统一异常处理
axiosObj.interceptors.request.use(function (config) {
  Object.keys(reqHeader).forEach(key=>{
    config.headers[key] = (<any>reqHeader)[key];
  })

  if (config.method == 'get') {
    config.data = true
  }
  config.headers['H-TOKEN'] = '111'
  return config;
}, function (error) {
  return Promise.reject(error);
})
axiosObj.interceptors.response.use((resp) => {
  //统一过滤
  return resp;
}, (err) => {
  //统一异常处理
  console.error(err);
});


let urlProxy: { [key: string]: any } = {};
const mockWait: Function[] = [];
function loadMock() {
  if (g.mockUrl == null) return;
  Axios.get<string[]>(`${g.mockUrl}`).then(resp => {
    // Axios.all(Axios.get())
    let all: any[] = [];
    resp.data.forEach(m => {
      all.push(Axios.get(`${m}`));
    });
    Axios.all(all).then(resp => {
      resp.forEach(m => {
        m.data.forEach((n: { url: string, action: string, result: any }) => {
          urlProxy[n.url + '_' + (n.action ? n.action.toUpperCase() : "GET")] = n.result;
        })
      })
      if (mockWait.length > 0) {
        for (let i = 0, l = mockWait.length; i < l; i++) {
          (<any>mockWait.pop())();
        }
      }
    })
  }).catch(() => {
    alert('mock数据加载失败,请修正相关配置')
  })
}

if (g.proxyService === true || (g.proxyServiceArr != null && Object.keys(g.proxyServiceArr).length > 0)) {
  //主动加载所有mock数据
  loadMock();
}



function fetchPath(urlPath: string, params: { [key: string]: any }) {
  if (g.proxyService === true && (g.excludeProxy == null || g.excludeProxy.find(m => m == urlPath) == null)) return urlPath;

  const m = urlPath.match(/\{[\w]+\}/g);
  if (m == null) return urlPath;

  m.forEach(n => {
    urlPath = urlPath.replace(n, params[n.replace(/^\{|\}$/g, '')]);
  })
  return urlPath;
}

function asyncAny<T>(url: string, action: 'POST' | 'GET'|'PUT', { params }: { params: any }) {
  return new Promise<T>(async (resolve) => {
    let resp;
    if (g.proxyService === true && (g.excludeProxy == null || g.excludeProxy.find(m => m == url) == null) || (g.proxyServiceArr != null && g.proxyServiceArr[url] != null)) {
      //走代理
      if (Object.keys(urlProxy).length == 0) {
        mockWait.push(() => {
          resolve(urlProxy[`${url}_${action}`]);
        })
      } else {
        resolve(urlProxy[`${url}_${action}`]);
      }
      return;
    }
    const reqPath = `${prePath}${url}`;
    Object.keys(params).forEach(m => {
      if (params[m] == null) {
        delete params[m];
      }
    });


    if (action == 'GET') {
      resp = await axiosObj.get(`${reqPath}`, {
        params
      });
    } else if(action == 'POST'){
      resp = await axiosObj.post(`${reqPath}`, qs.stringify(params))
    }else {
      resp = await axiosObj.put(`${reqPath}`, qs.stringify(params));
    }
    resolve(resp.data);
  });
}

export {
  asyncAny, fetchPath
}